
package com.ls.fw.mvc.struts.converter;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Map;

import org.apache.struts2.util.StrutsTypeConverter;

import com.ls.fw.commons.core.log.PlatLogger;
import com.ls.fw.commons.core.utils.date.DateTypeUtil;


public class DateTypeConverter extends StrutsTypeConverter {
   
	private static final PlatLogger LOG = new PlatLogger(DateTypeConverter.class);

    public static final String DEFAULT_DATE_FORMAT = "yyyy-MM-dd";
 
    //暂时只考虑这几种日期格式
    public static final DateFormat[] ACCEPT_DATE_FORMATS = {
        new SimpleDateFormat(DEFAULT_DATE_FORMAT)
        ,new SimpleDateFormat("yyyy年MM月dd日")
        ,new SimpleDateFormat("yyyy/MM/dd")
        };

    @Override
    public Object convertFromString(Map context, String[] values, Class toClass) {
        if (values[0] == null || values[0].trim().equals("")) {
            return null;
        }
        if (values[0].contains(":")) {
            try {
                return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(values[0]);
            } catch (ParseException e) {
                LOG.error("转换失败",e);
            }
        }else{
        	try {
                return new SimpleDateFormat("yyyy-MM-dd").parse(values[0]);
            } catch (ParseException e) {
                LOG.error("转换失败",e);
            }
        }
        for (DateFormat format : ACCEPT_DATE_FORMATS) {
            try {
                return format.parse(values[0]);
            } catch (    ParseException | RuntimeException e) {
                continue;
            }
        }
        LOG.debug("can not format date string:" + values[0]);
        return null;
    }
    
    @Override
    public String convertToString(Map context, Object o) {
        try {
    	   return DateTypeUtil.toString(o);
		} catch (ParseException e) {
			e.printStackTrace();
		}
        return "";
    }
}